package cn.szzsi._admin;


import cn.szzsi._Config;
import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.bean.dto.PayAttach;
import cn.szzsi.common.excel.ExcelReader;
import cn.szzsi.common.excel.PoiRender;
import cn.szzsi.common.kit.CommonUtil;

import cn.szzsi.common.kit.SerialNumberUtil;
import cn.szzsi.common.model.*;

import cn.szzsi.service.HtmlService;
import cn.szzsi.service.OrderService;
import cn.szzsi.service.UserBalanceDetailService;
import cn.szzsi.service.UserBalanceService;
import cn.szzsi.validator.OrderValidator;
import cn.szzsi.validator.RefundValidator;
import cn.szzsi.validator.ReshipValidator;
import cn.szzsi.validator.ShippingValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.JFinal;
import com.jfinal.kit.*;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.Render;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;

/**
 * 后台类 - 商户订单管理
 * Created by yuanzheng on 2016/10/13.
 */
public class OrderController extends BaseAdminController<Orders> {
    private Orders orders;
    private Payment payment;
    private Shipping shipping;//发货
    private Refund refund;//退款
    private Reship reship;//退货
    private String shopId;

    private List<OrderItem> orderItemList = new ArrayList<OrderItem>();
    private List<DeliveryItem> deliveryItemList = new ArrayList<DeliveryItem>();

    // 列表
    public void list() {
        String type = getPara("type");//订单类型
        String status = getPara("status");//订单状态
        if(StrKit.isBlank(type)){//总揽
            render("order_manage_list.html");
        }else{
            if(type.equalsIgnoreCase("wl")){//物流
                if("dfh".equalsIgnoreCase(status)){//待发货
                    render("order_manage_list_wl_dfh.html");
                }else if ("dsh".equalsIgnoreCase(status)){//待收货
                    render("order_manage_list_wl_dsh.html");
                }else if("ysh".equalsIgnoreCase(status)){//已收货
                    render("order_manage_list_wl_ysh.html");
                }
            }else{//财务
                render("order_manage_list_cw.html");
            }
        }
    }

    public void ajaxlist(){
        shopId=getAttr("shopId");
        SiteConfig siteConfig = SiteConfig.getByShopId(shopId);
        String sql = "select o.*,m.code,m.username from mall_orders o left join mall_member m on o.member_id=m.id where 1 = 1 ";
        String userId=getAttr("userId");
        if (siteConfig.getProductRank() == 1 && !shopId.equals(userId)) {//开启分管权限并且不是超级管理员
            sql = "select o.*,m.code ,m.username from mall_orders o left join mall_member m on o.member_id=m.id where o.id in(select distinct(order_id) from mall_order_item where product_id in (select id from mall_product where creator = '"+userId+"'))";
        }
        String status = getPara("status","dfk");
        if(status.equalsIgnoreCase("dfk")){//待付款
            sql += " and o.paymentStatus in (0,1) and  o.checks = 0 ";
        }else if(status.equalsIgnoreCase("yfk")){//已付款
            sql += " and o.paymentStatus = 2 and o.checks = 0 ";
        }else if(status.equalsIgnoreCase("dfh")){//待发货
            sql += " and o.shippingStatus in (0,1) and o.paymentStatus = 2 and o.checks = 1 ";
        }else if(status.equalsIgnoreCase("dsh")){//待收货
            sql += " and o.shippingStatus = 2 and o.paymentStatus = 2  and o.checks = 1  and orderStatus!=2";
        }else if(status.equalsIgnoreCase("ysh")){//已收货
            sql += " and o.orderStatus = 2 and o.paymentStatus = 2  and o.checks = 1 ";
        }else if(status.equalsIgnoreCase("tkz")){
            sql += " and o.paymentStatus = 5";
        }else if(status.equalsIgnoreCase("ytk")){
            sql += " and o.paymentStatus = 4";
        }

        //orderSn
        sql += getLikeSql("orderSn");
        // shipName
        sql += getLikeSql("shipName");
        // paymentStatus
        sql += getEquelSql("paymentStatus");
        // shippingStatus
        sql += getEquelSql("shippingStatus");
        // paymentConfigName
        sql += getLikeSql("paymentConfigName");
        // deliveryTypeName
        sql += getLikeSql("deliveryTypeName");
        // startCreateDate
        // endCreateDate
        sql += getTimeBetweenSql("startCreateDate","endCreateDate");

        if (StrKit.notBlank(getProperty()) && StrKit.notBlank(getKeyword())) {
            sql += "and " + getProperty() + " like '%" + getKeyword() + "%'";
        }

        sql += " and uid='"+shopId+"' order by " + getOrderBy() +" "+ getOrderType();
        List<Orders> ordersList = Orders.dao.find(sql);
        for(Orders o:ordersList){
            o.initParams();
        }
        renderJson(ordersList);
    }


    /**
     * 审核
     */
    public void check(){
        Orders o = Orders.dao.findById(getPara("id"));
        if(o != null){
            o.set("checks",1);
            o.update();
        }
        renderJson(true);
    }

    /**
     * 一键审核
     */
    public void batchcheck() {
        String[] ids = getParaValues("ids[]");
        Orders.dao.batchcheck(ids);
        renderJson(true);
    }


    private String getTimeBetweenSql(String start, String end){
        String startv = getPara(start);
        String endv = getPara(end);

        String sql = "";
        if(StrKit.notBlank(startv)){
            sql = " and o.createDate > '"+startv+"' ";
        }

        if(StrKit.notBlank(endv)){
            sql += " and o.createDate < '"+end+"' ";
        }
        return sql;
    }

    private String getEquelSql(String name){
        String value = getPara(name);
        if(StrKit.notBlank(value)){
            return " and o."+name+" = "+value+" ";
        }else{
            return "";
        }
    }

    private String getLikeSql(String name){
        String value = getPara(name);
        if(StrKit.notBlank(value)){
            return " and o."+name+" like '%"+value+"%' ";
        }else{
            return "";
        }
    }

    // 编辑
    public void edit() {
        String orderId = getPara("order.id","");
        if (StrKit.isBlank(orderId)){
            addActionError("订单ID不能为空！");
            return;
        }

        orders = Orders.dao.findById(orderId);
        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed || orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            addActionError("此订单状态无法编辑！");
            return;
        }
        if (orders.getPaymentStatusValue() != Orders.PaymentStatus.unpaid) {
            addActionError("此订单付款状态无法编辑！");
            return;
        }
        if (orders.getShippingStatusValue() != Orders.ShippingStatus.unshipped) {
            addActionError("此订单发货状态无法编辑！");
            return;
        }
        setAttr("orders", orders);
        setAttr("allDeliveryType", DeliveryType.dao.getAllDeliveryCorp());// 获取所有配送方式
        setAttr("allPaymentConfig", PaymentConfig.dao.getAll()); // 获取所有支付方式
        setAttr("allWeightUnit", getAllWeightUnit()); // 获取所有重量单位
        render(CommonUtil.TEMPLATE_PATH+"/admin/order_input.html");
    }

    // 更新
    @Before(OrderValidator.class)
    public void update() {
        orders = getModel(Orders.class);
        String productWeightUnit = getPara("productWeightUnit","");
        int orderItemSize = getParaToInt("orderItemSize",0);
        orders.set("productWeightUnit", Product.WeightUnit.valueOf(productWeightUnit).ordinal());

        // 统计产品行数
        for (int i = 1; i <= orderItemSize; i++) {
            orderItemList.add(getModel(OrderItem.class, "orderItem[" + i + "]"));
        }

        Orders persistent = Orders.dao.findById(orders.getStr("id"));
        if (persistent.getOrderStatusValue() == Orders.OrderStatus.completed || persistent.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            addActionError("此订单状态无法编辑！");
            return;
        }
        if (persistent.getPaymentStatusValue() != Orders.PaymentStatus.unpaid) {
            addActionError("此订单付款状态无法编辑！");
            return;
        }
        if (persistent.getShippingStatusValue() != Orders.ShippingStatus.unshipped) {
            addActionError("此订单配送状态无法编辑！");
            return;
        }
        if (orders.getBigDecimal("deliveryFee").compareTo(new BigDecimal("0")) < 0) {
            addActionError("配送费用不允许小于0！");
            return;
        }
        if (orders.getBigDecimal("deliveryFee").compareTo(new BigDecimal("0")) < 0) {
            addActionError("支付费用不允许小于0！");
            return;
        }
        if (orders.getDouble("productWeight") < 0) {
            addActionError("商品重量不允许小于0！");
            return;
        }
        if (StringUtils.isEmpty(orders.getStr("shipPhone")) && StringUtils.isEmpty(orders.getStr("shipMobile"))) {
            addActionError("联系电话、联系手机必须填写其中一项！");
            return;
        }
        if (orderItemList == null || orderItemList.size() == 0) {
            addActionError("请保留至少一个商品！");
            return;
        }
        if (!Area.dao.isAreaPath(orders.getStr("shipAreaPath"))) {
            addActionError("地区错误！");
            return;
        }
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getInt("productQuantity") <= 0) {
                addActionError("商品数量错误！");
                return;
            }
            if (orderItem.getBigDecimal("productPrice").compareTo(new BigDecimal("0")) < 0) {
                addActionError("商品价格错误！");
                return;
            }
            Product product = Product.dao.findById(OrderItem.dao.findById(orderItem.getStr("id")).getProduct().getStr("id"));
            if (product.getInt("store") != null) {
                OrderItem orderItemPersistent = OrderItem.dao.findById(orderItem.getStr("id"));
                Integer availableStore = 0;
                if ((getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.payment && orders.getPaymentStatusValue() == Orders.PaymentStatus.unpaid) ||
                        (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.ship && orders.getShippingStatusValue() == Orders.ShippingStatus.unshipped)) {
                    availableStore = product.getInt("store") - product.getInt("freezeStore");
                } else {
                    availableStore = product.getInt("store") - product.getInt("freezeStore") + orderItemPersistent.getInt("productQuantity");
                }
                if (orderItem.getInt("productQuantity") > availableStore) {
                    addActionError("商品[" + product.getStr("name") + "]库存不足！");
                    return;
                }
                if (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.order || (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.payment && orders.getPaymentStatusValue() != Orders.PaymentStatus.unpaid) ||
                        (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.ship && orders.getShippingStatusValue() != Orders.ShippingStatus.unshipped)) {
                    product.set("freezeStore",product.getInt("freezeStore") - orderItemPersistent.getInt("productQuantity") + orderItem.getInt("productQuantity"));
                    product.update();
                }
            }
        }
        DeliveryType deliveryType = orders.getDeliveryType();
        PaymentConfig paymentConfig = orders.getPaymentConfig();
        String paymentConfigName = null;
        if (paymentConfig != null && StringUtils.isNotEmpty(paymentConfig.getStr("id"))) {
            //paymentConfig = paymentConfigService.load(paymentConfig.getId());
            paymentConfigName = paymentConfig.getStr("name");
        } else {
            paymentConfig = null;
            paymentConfigName = "货到付款";
        }

        Integer productTotalQuantity = 0;// 商品总数
        BigDecimal productTotalPrice = new BigDecimal("0");// 商品总价格
        BigDecimal totalAmount = new BigDecimal("0");// 订单总金额
        for (OrderItem orderItem : orderItemList) {
            OrderItem orderItemPersistent = OrderItem.dao.findById(orderItem.getStr("id"));
            productTotalQuantity += orderItem.getInt("productQuantity");
            productTotalPrice = productTotalPrice.add(orderItem.getBigDecimal("productPrice").multiply(new BigDecimal(orderItem.getInt("productQuantity").toString())));
            orderItemPersistent.update();
        }
        for (OrderItem orderItem : persistent.getOrderItemList()) {
            if (!orderItemList.contains(orderItem)) {
                orderItem.delete();
            }
        }
        totalAmount = productTotalPrice.add(orders.getBigDecimal("deliveryFee")).add(orders.getBigDecimal("paymentFee"));
        orders.set("totalAmount", totalAmount);
        orders.set("orderStatus", Orders.OrderStatus.valueOf(Orders.OrderStatus.processed.name()).ordinal());
        orders.set("deliveryTypeName", deliveryType.getStr("name"));
        orders.set("paymentConfigName", paymentConfigName);
        orders.set("paymentConfig_id",paymentConfig.getStr("id"));
        orders.set("productTotalPrice", productTotalPrice);
        orders.set("productTotalQuantity",productTotalQuantity);
        orders.set("shipArea", Area.dao.getAreaString(orders.getStr("shipAreaPath")));
        updated(orders);

        // 订单日志
        OrderService.service.saveOrderLog(OrderLog.OrderLogType.modify.ordinal(),persistent,"订单修改");
        redirect("/order/list");
    }

    // 处理
    public void process() {
        shopId=getAttr("shopId");
        String orderId = getPara("orders.id", "");
        if (StrKit.isBlank(orderId)) {
            return;
        }
        orders = Orders.dao.findById(orderId);
        setAttr("orders", orders);
        setAttr("type",getPara("type",""));//判断是否财务人员登录
        setAttr("nonRechargePaymentTypeList", getNonRechargePaymentTypeList());
        setAttr("allPaymentConfig", PaymentConfig.dao.getByUid(CommonUtil.PLATFROM_FLAG));
        setAttr("allDeliveryType", getAllDeliveryType(shopId));
        setAttr("allDeliveryCorp", getAllDeliveryCorp());
        setAttr("refundTypeList", getRefundTypeList());
        String userId=getAttr("userId");//当前登录人id
        List<OrderItem> orderItemList= Orders.dao.getOrderItemList(orderId,userId,shopId,"dfh");
        setAttr("orderItemList",orderItemList);
        render("order_manage_process.html");
    }

    // 支付
    @Before(Tx.class)
    public void payment() {
        payment = getModel(Payment.class);
        String orderId = getPara("orders.id","");
        String paymentType = getPara("paymentType","");
        payment.set("paymentType", Payment.PaymentType.valueOf(paymentType).ordinal()); // 支付类型

        if (StrKit.isBlank(orderId)) {
            addActionError("订单ID不能为空！");
            return;
        }
        orders = Orders.dao.findById(orderId);

        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed || orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            addActionError("此订单状态无法支付！");
            return;
        }
        if (orders.getPaymentStatusValue() == Orders.PaymentStatus.paid || orders.getPaymentStatusValue() == Orders.PaymentStatus.partRefund || orders.getPaymentStatusValue() == Orders.PaymentStatus.refunded) {
            addActionError("此订单付款状态无法支付！");
            return;
        }
        if (payment.getPaymentTypeValue() == Payment.PaymentType.recharge) {
            addActionError("支付类型错误！");
            return;
        }
        if (payment.getBigDecimal("totalAmount").compareTo(new BigDecimal("0")) < 0) {
            addActionError("支付金额不允许小于0！");
            return;
        }
        if (payment.getBigDecimal("totalAmount").compareTo(orders.getBigDecimal("totalAmount").subtract(orders.getBigDecimal("paidAmount"))) > 0) {
            addActionError("支付金额超出订单需付金额！");
            return;
        }
        Deposit deposit = null;
        if (payment.getPaymentTypeValue() == Payment.PaymentType.deposit) {
            Member member = orders.getMember();
            if (payment.getBigDecimal("totalAmount").compareTo(member.getBigDecimal("deposit")) > 0) {
                addActionError("会员余存款余额不足！");
                return;
            }
            member.set("deposit",member.getBigDecimal("deposit").subtract(payment.getBigDecimal("totalAmount")));
            member.set("modifyDate", new Date());
            member.update();
            deposit = new Deposit();
            deposit.set("depositType", Deposit.DepositType.adminPayment.ordinal());
            deposit.set("credit",new BigDecimal("0"));
            deposit.set("debit",payment.getBigDecimal("totalAmount"));
            deposit.set("balance",member.getBigDecimal("deposit"));
            deposit.set("member_id",member.getStr("id"));
            deposit.save(deposit);
        }
        PaymentConfig paymentConfig = PaymentConfig.dao.findById(payment.getStr("paymentConfig_id"));
        payment.set("paymentConfigName",paymentConfig.getStr("name"));
        payment.set("paymentFee",new BigDecimal("0"));
        //payment.set("operator", ShiroUtils.getLoginAdminName());//待改进
        payment.set("paymentStatus", Payment.PaymentStatus.success.ordinal());
        if(deposit!=null){
            payment.set("deposit_id",deposit.getStr("id"));
        }
        payment.set("paymentSn", SerialNumberUtil.buildPaymentSn());
        payment.set("order_id",orders.getStr("id"));
        payment.set("payer",orders.getMember().getStr("username"));//
        payment.save(payment);

        // 库存处理
        if (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.payment && orders.getPaymentStatusValue() == Orders.PaymentStatus.unpaid && orders.getShippingStatusValue() == Orders.ShippingStatus.unshipped) {
            for (OrderItem orderItem : orders.getOrderItemList()) {
                Product product = orderItem.getProduct();
                if (product.getInt("store") != null) {
                    product.set("freezeStore",product.getInt("freezeStore") + orderItem.getInt("productQuantity"));
                    if (product.getIsOutOfStock()) {
                        orderItem.getProduct().getProductAttributeMapStore();
                    }
                    product.update();
                    if (product.getIsOutOfStock()) {
                        HtmlService.service.productContentBuildHtml(product);
                    }
                }
            }
        }

        orders.set("orderStatus", Orders.OrderStatus.processed.ordinal());
        if (payment.getBigDecimal("totalAmount").compareTo(orders.getBigDecimal("totalAmount").subtract(orders.getBigDecimal("paidAmount"))) == 0) {
            orders.set("paymentStatus", Orders.PaymentStatus.paid.ordinal());
        } else {
            orders.set("paymentStatus", Orders.PaymentStatus.partPayment.ordinal());
        }
        orders.set("paidAmount",orders.getBigDecimal("paidAmount").add(payment.getBigDecimal("totalAmount")));
        updated(orders);

        // 订单日志
        OrderService.service.saveOrderLog(OrderLog.OrderLogType.payment.ordinal(),orders,"订单支付(商户操作)");
        process();
    }

    //电商ID
    private String EBusinessID="1308326";
    //电商加密私钥，快递鸟提供，注意保管，不要泄漏
    private String AppKey="1a5f6e0a-33a4-4d96-bb92-2200d47fb3b3";
    //请求url, 正式环境地址：http://api.kdniao.cc/api/Eorderservice    测试环境地址：http://testapi.kdniao.cc:8081/api/EOrderService
    private String ReqURL="http://testapi.kdniao.cc:8081/api/Eorderservice";//测试环境
    // 发货
    @Before({ShippingValidator.class,Tx.class})
    public void shipping() {
        shopId=getAttr("shopId");
        shipping = getModel(Shipping.class);
        String orderId = getPara("orders.id");

        String shipArea=getPara("receiver.province")+" "+getPara("receiver.city")+" "+getPara("receiver.area");
        if (StrKit.isBlank(orderId)){
            addActionError("订单ID不能为空！");
            return;
        }
        orders = Orders.dao.findById(orderId);
        int orderItemSize = getParaToInt("orderItemSize",0);

        // 统计产品行数
        for (int i = 1; i <= orderItemSize; i++) {
            deliveryItemList.add(getModel(DeliveryItem.class, "deliveryItemList[" + i + "]"));
        }

        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed || orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            addActionError("此订单状态无法发货！");
            return;
        }
        if (orders.getShippingStatusValue() == Orders.ShippingStatus.shipped) {
            addActionError("此订单配送状态无法发货！");
            return;
        }
        if (shipping.getBigDecimal("deliveryFee").compareTo(new BigDecimal("0")) < 0) {
            addActionError("物流费用不允许小于0！");
            return;
        }
        if (StringUtils.isEmpty(orders.getStr("shipPhone")) && StringUtils.isEmpty(orders.getStr("shipMobile"))) {
            addActionError("联系电话、联系手机必须填写其中一项！");
            return;
        }
        List<OrderItem> orderItemList = orders.getOrderItemList();
        int totalDeliveryQuantity = 0;// 总发货数
        OrderItem orderItemTotal= OrderItem.dao.findFirst("select IFNULL(sum(productQuantity),0)total from mall_order_item where order_id=? and totalDeliveryQuantity ='0'",orderId);
        Integer total=Integer.parseInt(orderItemTotal.getLong("total").toString());
        for (DeliveryItem deliveryItem : deliveryItemList) {
            Product product = Product.dao.findById(deliveryItem.getStr("product_id"));
            Integer deliveryQuantity = deliveryItem.getInt("deliveryQuantity");
            if(deliveryQuantity==null){
                continue;
            }
            if (deliveryQuantity < 0) {
                addActionError("发货数不允许小于0！");
                return;
            }
            totalDeliveryQuantity += deliveryQuantity;
            boolean isExist = false;
            for (OrderItem orderItem : orderItemList) {
                if (product.getStr("id").equals(orderItem.getStr("product_id"))) {
                    if (deliveryQuantity > (orderItem.getInt("productQuantity") - orderItem.getInt("deliveryQuantity"))) {
                        addActionError("发货数超出订单购买数！");
                        return;
                    }
                    if (product.get("store") != null) {
                        if ((getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.payment && orders.getPaymentStatusValue() == Orders.PaymentStatus.unpaid && orders.getShippingStatusValue() == Orders.ShippingStatus.unshipped) || (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.ship && orders.getShippingStatusValue() == Orders.ShippingStatus.unshipped)) {
                            if (deliveryQuantity > (product.getInt("store") - product.getInt("freezeStore"))) {
                                addActionError("商品[" + orderItem.getProduct().getStr("name") + "]库存不足！");
                                return;
                            }
                        } else {
                            if (orderItem.getInt("totalDeliveryQuantity") < orderItem.getInt("productQuantity") && deliveryQuantity > (product.getInt("store") - product.getInt("freezeStore") + orderItem.getInt("productQuantity") - orderItem.getInt("deliveryQuantity"))) {
                                addActionError("商品[" + orderItem.getProduct().getStr("name") + "]库存不足！");
                                return;
                            } else if (orderItem.getInt("totalDeliveryQuantity") >= orderItem.getInt("productQuantity") && deliveryQuantity > (product.getInt("store") - product.getInt("freezeStore"))) {
                                addActionError("商品[" + orderItem.getProduct().getStr("name") + "]库存不足！");
                                return;
                            }
                        }
                    }
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                addActionError("发货商品未在订单中！");
                return;
            }
        }
        if (totalDeliveryQuantity < 1) {
            renderJson(Ret.fail("info","发货总数必须大于0！"));
            return;
        }
        DeliveryType deliveryType = DeliveryType.dao.findById(shipping.getDeliverytypeId());
        shipping.set("shipArea",shipArea);
        shipping.set("order_id",orders.getId());
        shipping.set("deliveryTypeName",deliveryType.getName());
        shipping.set("shippingSn", SerialNumberUtil.buildShippingSn());
        shipping.set("uid",shopId);
        shipping.set("deliveryCorpName",getPara("shipping.deliveryCorpName"));
        shipping.save(shipping);

        // 库存处理
        if ((getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.payment && orders.getPaymentStatusValue() == Orders.PaymentStatus.unpaid && orders.getShippingStatusValue() == Orders.ShippingStatus.unshipped) || (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.ship && orders.getShippingStatusValue() == Orders.ShippingStatus.unshipped)) {
            for (OrderItem orderItem : orders.getOrderItemList()) {
                Product product = orderItem.getProduct();
                if (product.getStr("store") != null) {
                    product.set("freezeStore",product.getInt("freezeStore") + orderItem.getInt("productQuantity"));
                    if (product.getIsOutOfStock()) {
                        orderItem.getProduct().getProductAttributeMapStore();
                    }
                    product.update();
                    if (product.getIsOutOfStock()) {
                        HtmlService.service.productContentBuildHtml(product);
                    }
                }
            }
        }

        Orders.ShippingStatus shippingStatus = Orders.ShippingStatus.shipped;// 发货状态
        for (DeliveryItem deliveryItem : deliveryItemList) {
            if(deliveryItem.getProductId()==null){
                continue;
            }
            Product product = Product.dao.findById(deliveryItem.getProductId());
            for (OrderItem orderItem : orderItemList) {
                if (orderItem.getStr("product_id").equals(product.getId())) {
                    orderItem.set("totalDeliveryQuantity",orderItem.getTotalDeliveryQuantity() + deliveryItem.getDeliveryQuantity());
                    orderItem.update();
                    /*if (orderItem.getProductQuantity() > orderItem.getDeliveryQuantity()) {
                        shippingStatus = Orders.ShippingStatus.partShipped;
                    }*/
                    // 库存处理
                    if (product.getInt("store") != null) {
                        if (orderItem.getInt("totalDeliveryQuantity") <= orderItem.getInt("productQuantity")) {
                            product.set("freezeStore",product.getInt("freezeStore") - deliveryItem.getInt("deliveryQuantity"));
                        }
                        product.set("store",product.getInt("store") - deliveryItem.getInt("deliveryQuantity"));
                        if (product.getIsOutOfStock()) {
                            product.getProductAttributeMapStore();
                        }
                        product.update();
                        if (product.getIsOutOfStock()) {
                            HtmlService.service.productContentBuildHtml(product);
                        }
                    }
                    break;
                }
            }

            if(total>totalDeliveryQuantity){
                shippingStatus = Orders.ShippingStatus.partShipped;
            }
            deliveryItem.set("productSn", product.getStr("productSn"));
            deliveryItem.set("productName", product.getStr("name"));
            deliveryItem.set("productHtmlFilePath", product.getStr("htmlFilePath"));
            deliveryItem.set("shipping_id", shipping.getStr("id"));
            deliveryItem.save(deliveryItem);
        }
        orders.set("shippingStatus",shippingStatus.ordinal());
        updated(orders);

        // 订单日志
        OrderService.service.saveOrderLog(OrderLog.OrderLogType.shipping.ordinal(),orders,"订单发货(商户操作)");
        process();
    }


    // 完成
    @Before(Tx.class)
    public void completed() {
        String orderId = getPara("orders.id", "");
        if (StrKit.isBlank(orderId)) {
            addActionError("订单ID不能空！");
            return;
        }
        orders = Orders.dao.findById(orderId);

        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed) {
            ajaxJsonWarnMessage("此订单已经完成！");
        } else if (orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            ajaxJsonErrorMessage("此订单已经作废！");
        } else {
            orders.set("orderStatus", Orders.OrderStatus.valueOf(Orders.OrderStatus.completed.name()).ordinal());
            updated(orders);

            // 积分处理
            Integer totalPoint = 0;
            if (getSystemConfig().getPointType() == SystemConfig.PointType.orderAmount) {
                totalPoint = orders.getBigDecimal("productTotalPrice").multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
            } else if (getSystemConfig().getPointType() == SystemConfig.PointType.productSet) {
                for (OrderItem orderItem : orders.getOrderItemList()) {
                    totalPoint = orderItem.getProduct().getInt("point") * orderItem.getInt("productQuantity") + totalPoint;
                }
            }
            if (totalPoint > 0) {
                Member member = orders.getMember();
                member.set("point",member.getInt("point") + totalPoint);
                MemberRank upMemberRank = MemberRank.dao.getUpMemberRankByPoint(member.getInt("point"),member.getStr("shopId"));
                if (upMemberRank != null && member.getInt("point") >= upMemberRank.getInt("point")) {
                    member.set("memberRankId",upMemberRank.getStr("id"));
                }
                member.update();
            }
            // 订单日志
            OrderService.service.saveOrderLog(OrderLog.OrderLogType.completed.ordinal(),orders,"订单完成(商户操作)");
            ajaxJsonSuccessMessage("您的操作已成功！");
        }
    }

    // 作废
    public void invalid() {
        String orderId = getPara("orders.id", "");
        if (StrKit.isBlank(orderId)) {
            addActionError("订单ID不能空！");
            return;
        }
        orders = Orders.dao.findById(orderId);
        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed || orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            addActionError("此订单状态无法编辑！");
            return;
        }
        if (orders.getPaymentStatusValue() != Orders.PaymentStatus.unpaid) {
            addActionError("此订单支付状态无法编辑！");
            return;
        }
        if (orders.getShippingStatusValue() != Orders.ShippingStatus.unshipped) {
            addActionError("此订单发货状态无法编辑！");
            return;
        }

        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed) {
            ajaxJsonWarnMessage("此订单已经完成！");
        } else if (orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            ajaxJsonErrorMessage("此订单已经作废！");
        } else if (orders.getPaymentStatusValue() != Orders.PaymentStatus.unpaid) {
            ajaxJsonErrorMessage("此订单付款状态无法作废！");
        } else if (orders.getShippingStatusValue() != Orders.ShippingStatus.unshipped) {
            ajaxJsonErrorMessage("此订单配送状态无法作废！");
        } else {
            orders.set("orderStatus", Orders.OrderStatus.valueOf(Orders.OrderStatus.invalid.name()).ordinal());
            updated(orders);
            // 库存处理
            if (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.order || (getSystemConfig().getStoreFreezeTime() == SystemConfig.StoreFreezeTime.payment && orders.getPaymentStatusValue() != Orders.PaymentStatus.unpaid) || orders.getShippingStatusValue() != Orders.ShippingStatus.unshipped) {
                for (OrderItem orderItem : orders.getOrderItemList()) {
                    Product product = orderItem.getProduct();
                    product.set("freezeStore", product.getInt("freezeStore") - orderItem.getInt("productQuantity"));
                    if (!product.getIsOutOfStock()) {
                        orderItem.getProduct().getProductAttributeMapStore();
                    }
                    product.set("modifyDate", new Date());
                    product.update();
                    if (!product.getIsOutOfStock()) {
                        HtmlService.service.productContentBuildHtml(product);
                    }
                }
            }
            // 订单日志
            OrderService.service.saveOrderLog(OrderLog.OrderLogType.invalid.ordinal(),orders,"订单作废(商户操作)");
            ajaxJsonSuccessMessage("您的操作已成功！");
        }
    }

    // 查看
    public void view() {
        shopId=getAttr("shopId");
        String orderId = getPara("orders.id", "");
        if (StrKit.notBlank(orderId)) {
            orders = Orders.dao.findById(orderId);
        }
        setAttr("order", orders);
        String userId=getAttr("userId");//当前登录人id

        List<OrderItem> orderItemList= Orders.dao.getOrderItemList(orders.getId(),userId,shopId,"");
        setAttr("orderItemList",orderItemList);
        render("order_manage_view.html");
    }

    //导出待发货订单
    public void exportNotShipped(){
        String shopId=getAttr("shopId");
        String sql="SELECT o.orderSn,oi.productSn,oi.productName,oi.productQuantity,o.shipName,o.shipMobile,o.shipAreaPath,o.shipAddress,o.deliveryTypeName,o.memo,oi.product_id,p.specificationvalues FROM `mall_order_item` oi LEFT JOIN mall_orders o ON oi.order_id=o.id LEFT JOIN mall_product p on oi.product_id=p.id  where o.shippingStatus in (0,1) and o.paymentStatus = 2 and o.checks = 1 and o.uid=? order by o.createDate,o.orderSn";
        List<OrderItem>orderItems= OrderItem.dao.find(sql,shopId);
        List list=new ArrayList();
        for(OrderItem orderItem:orderItems){
            Map<String,Object>map=new HashedMap();
            map.put("orderSn",orderItem.get("orderSn"));
            map.put("productSn",orderItem.get("productSn"));
            map.put("productName",orderItem.get("productName"));
            map.put("totalDeliveryQuantity",orderItem.get("productQuantity"));
            map.put("shipName",orderItem.get("shipName"));
            map.put("shipMobile",orderItem.get("shipMobile"));
            map.put("shipAreaPath",orderItem.get("shipAreaPath"));
            map.put("shipAddress",orderItem.get("shipAddress"));
            map.put("deliveryTypeName",orderItem.get("deliveryTypeName"));
            map.put("memo",orderItem.get("memo"));
            map.put("valuenames", Product.dao.getSpecificationvaluesAll(orderItem.getProduct()));
            list.add(map);

        }
        String[] header={"订单编号","商品编号","商品名称","商品规格","件数","联系人","联系方式","收货城市","收货地址","发货方式","发货备注"};
        String[] columns={"orderSn","productSn","productName","valuenames","totalDeliveryQuantity","shipName","shipMobile","shipAreaPath","shipAddress","deliveryTypeName","memo"};
        Render poirender = PoiRender.me(list).fileName("deliver.xls").headers(header).sheetName("deliver").columns(columns);
        render(poirender);
    }

    /**
     * 下载导入示例
     */
    public void exportDemo(){
        List list=new ArrayList();
        Map<String,Object>map=new HashedMap();
        map.put("orderSn",4345135);
        map.put("productSn","SN_E9388238A8FE");
        map.put("deliverySn","4548484884848");
        map.put("totalDeliveryQuantity",2);
        list.add(map);
        String[] header={"订单编号","商品编号","发货数量","物流单号"};
        String[] columns={"orderSn","productSn","totalDeliveryQuantity","deliverySn"};
        Render poirender = PoiRender.me(list).fileName("demo.xls").headers(header).sheetName("demo").columns(columns);
        render(poirender);
    }

    /**
     * 导入线下发货订单,同步订单状态
     */
    @Before(Tx.class)
    public void importHasShipped(){
        shopId=getAttr("shopId");
        UploadFile uploadFile = getFile("orderFile");
        File filExcel = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+uploadFile.getFileName());//默认文件路径
        ExcelReader excelReader=new ExcelReader();//new 一个对象
        try {
            InputStream is = new FileInputStream(filExcel);
            Map<Integer, List> map = excelReader.readExcelContent(is);
            String msgStr="";
            Integer errorCount=0;
            for(int i=1;i<=map.size();i++){//多少行
                List<String> list=map.get(i);
                for(int j=0;j<list.size();j++){//取出每行数据
                    String orderSn=list.get(0);//订单编号
                    String productSn=list.get(1);//商品编码
                    String deliveryQuantity=list.get(2);//该商品发货数量
                    String deliverySn=list.get(3);//物流单号
                    Orders orders= Orders.dao.getOrderBySN(orderSn);//查询订单详情
                    if(orders==null){
                        msgStr+=(i+1)+"行,";
                        errorCount++;
                        break;
                    }
                    //暂且将订单状态更改为全部发货,如后面需求变,再变
                    orders.setShippingStatus(2);//已发货


                    OrderItem orderItem= OrderItem.dao.getByOrderIdAndProductSn(orders.getId(),productSn);
                    if(orderItem==null){
                        msgStr+=(i+1)+"行,";
                        errorCount++;
                        break;
                    }
                    orderItem.setTotalDeliveryQuantity(Integer.valueOf(deliveryQuantity));

                    //保存物流信息
                    Shipping shipping=Shipping.dao.getByOrderIdAndDeliverSn(orders.getId(),deliverySn);
                    if(shipping==null){
                        Shipping addShipping=new Shipping();
                        addShipping.set("uid",shopId);
                        addShipping.set("shipArea",orders.getShipArea());
                        addShipping.set("order_id",orders.getId());
                        addShipping.set("deliveryTypeName",orders.getDeliveryType().getName());
                        addShipping.set("shippingSn", SerialNumberUtil.buildShippingSn());
                        addShipping.set("deliveryCorpName",orders.getDeliveryCorp().getName());
                        addShipping.set("deliverySn",deliverySn);
                        addShipping.setDeliveryFee(orders.getDeliveryFee());
                        addShipping.setShipAddress(orders.getShipAddress());
                        addShipping.setShipName(orders.getShipName());
                        addShipping.setShipMobile(orders.getShipMobile());
                        addShipping.set("shipZipCode","000000");
                        addShipping.save(addShipping);

                    }
                    orders.update();//更新订单
                    orderItem.update();//更新订单明细

                }

            }
            if(filExcel!=null){
                filExcel.delete();
            }
            if(msgStr.length()>=0){
                msgStr="第"+msgStr+"数据有误,请检查是否正确!";
            }
            if(errorCount==0){
                renderJson(Ret.ok("info","更新成功,共有"+map.size()+"条记录,同步成功!"));
            }else{
                renderJson(Ret.ok("info","更新成功,共有"+map.size()+"条记录,同步成功"+(map.size()-errorCount)+"条,其中"+msgStr));
            }

        }catch (Exception e){
            renderJson(Ret.fail("info","同步失败!"));
            System.out.println("报错---------------------"+e.getMessage());
            e.printStackTrace();
        }
    }



    // 退款
    @Before({RefundValidator.class,Tx.class})
    public void recheckfund() {
        shopId=getAttr("shopId");
        String refundType = getPara("refundType","");
        String ordersId = getPara("orders.id","");
        refund = getModel(Refund.class);
        refund.set("refundType", Refund.RefundType.valueOf(refundType).ordinal());

        if (StrKit.isBlank(ordersId)){
            addActionError("订单ID不能为空！");
            return;
        }
        orders = Orders.dao.findById(ordersId);
        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed || orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            addActionError("此订单状态无法退款！");
            return;
        }
        if (orders.getPaymentStatusValue() == Orders.PaymentStatus.unpaid || orders.getPaymentStatusValue() == Orders.PaymentStatus.refunded) {
            addActionError("此订单付款状态无法支付！");
            return;
        }
        if (refund.getBigDecimal("totalAmount").compareTo(new BigDecimal("0")) < 0) {
            addActionError("退款金额不允许小于0！");
            return;
        }
        if (refund.getBigDecimal("totalAmount").compareTo(orders.getBigDecimal("paidAmount")) > 0) {
            addActionError("退款金额超出订单已付金额！");
            return;
        }
        Deposit deposit = null;

        PaymentConfig paymentConfig = PaymentConfig.dao.findById(refund.getStr("paymentConfig_id"));
        refund.set("paymentConfigName",paymentConfig.getStr("name"));
        //refund.set("operator",getLoginAdminName());//待处理
        if(deposit!=null){
            refund.set("deposit_id",deposit.getStr("id"));
        }

        refund.set("order_id",orders.getStr("id"));
        refund.set("refundSn", SerialNumberUtil.buildRefundSn());
        refund.set("uid",shopId);


        orders.set("orderStatus", Orders.OrderStatus.processed.ordinal());
        if (refund.getBigDecimal("totalAmount").compareTo(orders.getBigDecimal("paidAmount")) < 0) {
            orders.set("paymentStatus", Orders.PaymentStatus.partRefund.ordinal());
        } else {
            orders.set("paymentStatus", Orders.PaymentStatus.refunded.ordinal());
        }
        //orders.set("paidAmount",orders.getBigDecimal("paidAmount").subtract(refund.getBigDecimal("totalAmount")));

        if(paymentConfig.getPaymentConfigTypeValue()==PaymentConfig.PaymentConfigType.weixin){//微信支付(退款)
            String appid= _Config.p.get("wechat_appid");//AppID(应用ID)
            String partner=  _Config.p.get("weichat_bargainorId");//商户id
            String partnerKey=_Config.p.get("weichat_key");//商户支付秘钥

            Map<String,String> params = new HashMap<String, String>();
            params.put("appid", appid);//AppID(应用ID)
            params.put("mch_id", partner);//商户号
            params.put("nonce_str", System.currentTimeMillis() / 1000 + "");//随机字符串，不长于32位

            params.put("transaction_id",orders.getTradeNo());//微信订单号
            params.put("out_refund_no",refund.getRefundSn());//商户退款单号
            BigDecimal total_fee=orders.getPaidAmount().multiply(new BigDecimal("100"));
            total_fee=total_fee.setScale(0,BigDecimal.ROUND_HALF_UP);
            params.put("total_fee", total_fee.toString());//订单总金额，单位为分，只能为整数，详见支付金额
            params.put("refund_fee",total_fee.toString());//退款金额退款总金额，订单总金额，单位为分，只能为整数，详见支付金额
            String sign = PaymentKit.createSign(params, partnerKey);//支付秘钥
            params.put("sign", sign);
            String certPath=PathKit.getWebRootPath()+File.separator+"cert"+File.separator+"apiclient_cert.p12";
            Map<String,String> xmlResult = PaymentApi.refund(params,partnerKey,certPath);
            if(!"SUCCESS".equals(xmlResult.get("return_code"))){

            }else{
                renderJson(xmlResult);
            }
        }

        // 订单日志
        OrderService.service.saveOrderLog(OrderLog.OrderLogType.refund.ordinal(),orders,"退款(商户操作)");
        if (refund.getRefundTypeValue() == Refund.RefundType.deposit) {
            Member member = orders.getMember();
            //UserBalanceService.service.updateBalance(member,refund.getBigDecimal("totalAmount"));//更新会员余额结果
            UserBalanceDetailService.service.saveAdminRefund(member.getStr("id"),refund.getBigDecimal("totalAmount"), UserBalanceDetail.BalanceType.adminRefund.ordinal(),shopId,orders.getStr("orderSn"));//后台退款明细
        }

        refund.save(refund);
        orders.update();
        process();
    }

    /**
     * 退款接口(新)
     */
    @Before(Tx.class)
    public void refund(){
        shopId=getAttr("shopId");
        String orderId = getPara("orders.id","");//订单编号
        orders = Orders.dao.findById(orderId);//订单表
        System.out.println(orders.getPaymentConfig());
        PaymentConfig.PaymentConfigType paymentConfigType=orders.getPaymentConfig().getPaymentConfigTypeValue();
        if(PaymentConfig.PaymentConfigType.weixin==paymentConfigType){//微信支付
            Map<String,String> params = new HashMap<String, String>();
            params.put("appid", "wx4ac0cb1815c599f8");//AppID(应用ID)
            params.put("mch_id", "1365876902");//商户号
            params.put("nonce_str", System.currentTimeMillis() / 1000 + "");//随机字符串，不长于32位

            params.put("transaction_id",orders.getTradeNo());//微信订单号
            params.put("out_refund_no","121231");//商户退款单号
            BigDecimal total_fee=orders.getPaidAmount().multiply(new BigDecimal("100"));
            total_fee=total_fee.setScale(0,BigDecimal.ROUND_HALF_UP);
            params.put("total_fee", total_fee.toString());//订单总金额，单位为分，只能为整数，详见支付金额
            params.put("refund_fee",total_fee.toString());//退款金额退款总金额，订单总金额，单位为分，只能为整数，详见支付金额
            String sign = PaymentKit.createSign(params, "8ikk7ujm6yhn5tgb4rfv3edc3edc5tga");//支付秘钥
            params.put("sign", sign);
            String certPath=PathKit.getWebRootPath()+File.separator+"cert"+File.separator+"apiclient_cert.p12";
            Map<String,String> xmlResult = PaymentApi.refund(params,"8ikk7ujm6yhn5tgb4rfv3edc3edc5tga",certPath);
            System.out.println(xmlResult);

        }


    }

    // 退货
    @Before({ReshipValidator.class,Tx.class})
    public void reship() {
        shopId=getAttr("shopId");
        String ordersId = getPara("orders.id","");
        reship = getModel(Reship.class);
        int orderItemSize = getParaToInt("orderItemSize",0);
        // 统计产品行数
        for (int i = 1; i <= orderItemSize; i++) {
            deliveryItemList.add(getModel(DeliveryItem.class, "deliveryItemList[" + i + "]"));
        }
        if (StrKit.isBlank(ordersId)) {
            addActionError("此订单ID不能为空！");
            return;
        }
        orders = Orders.dao.findById(ordersId);

        //订单已完成,并且订单不是退货中,并且订单没作废
        if (orders.getOrderStatusValue() == Orders.OrderStatus.completed && orders.getShippingStatusValue()!= Orders.ShippingStatus.inReshiped || orders.getOrderStatusValue() == Orders.OrderStatus.invalid) {
            addActionError("此订单状态无法退货！");
            return;
        }
        if (orders.getShippingStatusValue() == Orders.ShippingStatus.unshipped || orders.getShippingStatusValue() == Orders.ShippingStatus.reshiped) {
            addActionError("此订单配送状态无法退货！");
            return;
        }
        if (reship.getBigDecimal("deliveryFee").compareTo(new BigDecimal("0")) < 0) {
            addActionError("物流费用不允许小于0！");
            return;
        }
        if (!Area.dao.isAreaPath(reship.getStr("shipAreaPath"))) {
            addActionError("地区错误！");
            return;
        }
        if (StringUtils.isEmpty(orders.getStr("shipPhone")) && StringUtils.isEmpty(orders.getStr("shipMobile"))) {
            addActionError("联系电话、联系手机必须填写其中一项！");
            return;
        }
        //orders = orderService.load(orders.getId());
        List<OrderItem> orderItemSet = orders.getOrderItemList();
        int totalDeliveryQuantity = 0;// 总退货数
        for (DeliveryItem deliveryItem : deliveryItemList) {
            Product product = Product.dao.findById(deliveryItem.getStr("product_id"));
            Integer deliveryQuantity = deliveryItem.getInt("deliveryQuantity");
            if (deliveryQuantity < 0) {
                addActionError("退货数不允许小于0！");
                return;
            }
            totalDeliveryQuantity += deliveryQuantity;
            boolean isExist = false;
            for (OrderItem orderItem : orderItemSet) {
                if (product.getStr("id").equals(orderItem.getStr("product_id"))) {
                    if (deliveryQuantity > orderItem.getInt("deliveryQuantity")) {
                        addActionError("退货数超出已发货数！");
                        return;
                    }
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                addActionError("退货商品未在订单中！");
                return;
            }
        }
        if (totalDeliveryQuantity < 1) {
            addActionError("退货总数必须大于0！");
            return;
        }

        DeliveryType deliveryType = DeliveryType.dao.findById(reship.getStr("deliveryType_id"));
        reship.set("shipArea", Area.dao.getAreaString(reship.getStr("shipAreaPath")));
        reship.set("order_id",orders.getStr("id"));
        reship.set("deliveryTypeName",deliveryType.getStr("name"));
        reship.set("reshipSn", SerialNumberUtil.buildReshipSn());
        reship.set("uid",shopId);
        reship.save(reship);

        Orders.ShippingStatus shippingStatus = Orders.ShippingStatus.reshiped;// 配送状态
        for (DeliveryItem deliveryItem : deliveryItemList) {
            Product product = Product.dao.findById(deliveryItem.getStr("product_id"));
            for (OrderItem orderItem : orderItemSet) {
                if (orderItem.getStr("product_id").equals(product.getStr("id"))) {
                    orderItem.set("deliveryQuantity",orderItem.getInt("deliveryQuantity") - deliveryItem.getInt("deliveryQuantity"));
                    orderItem.update();
                    if (orderItem.getInt("deliveryQuantity") > deliveryItem.getInt("deliveryQuantity")) {
                        shippingStatus = Orders.ShippingStatus.partReshiped;
                    }
                }
            }
            deliveryItem.set("productSn",product.getStr("productSn"));
            deliveryItem.set("productName",product.getStr("name"));
            deliveryItem.set("productHtmlFilePath",product.getStr("htmlFilePath"));
            deliveryItem.set("reship_id",reship.getStr("id"));
            deliveryItem.save(deliveryItem);
        }
        orders.set("shippingStatus",shippingStatus.ordinal());
        updated(orders);

        // 订单日志
        OrderService.service.saveOrderLog(OrderLog.OrderLogType.reship.ordinal(),orders,"订单退货(商户操作)");
        process();
    }

    // 获取所有重量单位
    public List<Product.WeightUnit> getAllWeightUnit() {
        List<Product.WeightUnit> allWeightUnit = new ArrayList<Product.WeightUnit>();
        for (Product.WeightUnit weightUnit : Product.WeightUnit.values()) {
            allWeightUnit.add(weightUnit);
        }
        return allWeightUnit;
    }

    // 获取支付类型（不包含在线充值）
    public List<Payment.PaymentType> getNonRechargePaymentTypeList() {
        List<Payment.PaymentType> paymentTypeList = new ArrayList<Payment.PaymentType>();
        for (Payment.PaymentType paymentType : Payment.PaymentType.values()) {
            if (paymentType != Payment.PaymentType.recharge) {
                paymentTypeList.add(paymentType);
            }
        }
        return paymentTypeList;
    }

    // 获取退款类型
    public List<Refund.RefundType> getRefundTypeList() {
        List<Refund.RefundType> refundTypeList = new ArrayList<Refund.RefundType>();
        for (Refund.RefundType refundType : Refund.RefundType.values()) {
            refundTypeList.add(refundType);
        }
        return refundTypeList;
    }

    // 获取所有支付方式
    public List<PaymentConfig> getAllPaymentConfig() {
        return PaymentConfig.dao.getAll();
    }

    // 获取所有配送方式
    public List<DeliveryType> getAllDeliveryType(String shopId) {
        return DeliveryType.dao.getAllByUid(shopId);
    }

    // 获取所有物流公司
    public List<DeliveryCorp> getAllDeliveryCorp() {
        return DeliveryCorp.dao.getAll();
    }




    /**
     * Json方式 电子面单
     * @throws Exception
     * OrderCode : 订单编号
     * ShipperCode : 快递公司编码
     */
    public String orderOnlineByJson(String requestData) throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        params.put("RequestData", urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", EBusinessID);
        params.put("RequestType", "1007");
        String dataSign=encrypt(requestData, AppKey, "UTF-8");
        params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "2");

        //String result=sendPost(ReqURL, params);
        String result= HttpKit.get(ReqURL,params);

        //根据公司业务处理返回的信息......

        return result;
    }
    /**
     * MD5加密
     * @param str 内容
     * @param charset 编码方式
     * @throws Exception
     */
    @SuppressWarnings("unused")
    private String MD5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    /**
     * base64编码
     * @param str 内容
     * @param charset 编码方式
     * @throws UnsupportedEncodingException
     */
    private String base64(String str, String charset) throws UnsupportedEncodingException{
        String encoded = Base64.encode(str.getBytes(charset));
        return encoded;
    }

    @SuppressWarnings("unused")
    private String urlEncoder(String str, String charset) throws UnsupportedEncodingException{
        String result = URLEncoder.encode(str, charset);
        return result;
    }

    /**
     * 电商Sign签名生成
     * @param content 内容
     * @param keyValue Appkey
     * @param charset 编码方式
     * @throws UnsupportedEncodingException ,Exception
     * @return DataSign签名
     */
    @SuppressWarnings("unused")
    private String encrypt (String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception
    {
        if (keyValue != null)
        {
            return base64(MD5(content + keyValue, charset), charset);
        }
        return base64(MD5(content, charset), charset);
    }



}
